package newapproach.writer;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class XmlElement {

	private String name;

	private Map<String,String> attributes;

	private Collection<XmlElement> content;

	private String textContent;

	public XmlElement(String simpleName, Map<String, String> att,
			List<XmlElement> xmlContent) {
		init(simpleName,att,xmlContent);
	}

	public XmlElement(String simpleName, Map<String, String> att,
			XmlElement xmlContent) {
		init(simpleName,att,Collections.singleton(xmlContent));
	}

	public XmlElement(String simpleName, Map<String, String> att,
			String textContent) {
		init(simpleName,att,textContent);
	}

	private void init(String simpleName, Map<String, String> att,
			Collection<XmlElement> xmlContent) {
		name = simpleName;
		attributes = att;
		if(xmlContent!=null){
			content = xmlContent;
		}else{
			textContent = "";
		}
	}

	private void init(String simpleName, Map<String, String> att,
			String text) {
		name = simpleName;
		attributes = att;
		textContent = text;
	}

	@Override
	public String toString() {
		return "<"+ name  +printAttributes() +">"+
				printContent()				
				+"</"+name+">";
	}

	private String printContent() {
		String str = "";
		if(content != null && content.size() > 0){
			for(XmlElement c : content){
				str+=c.toString();
			}
		}else{
			str = textContent != null ? textContent : "";
		}
		return str;
	}

	private String printAttributes() {
		if(attributes == null){
			return "";
		}
		String str = "";
		for(Entry<String,String> att : attributes.entrySet()){
			str+= " " + att.getKey()+"=\""+att.getValue()+"\"";
		}
		return str;
	}


}
